<?php
require_once("../includes/configure.php");
global $SOAP_CLIENT;

$FILTERS_GROUPS = array('USER_INFORMATIONS'=>'ALL');
$GROUP_VALIDATOR = "VALIDATOR_%";
$GROUP_VALIDATOR_ICF = "VALIDATOR_ICF_%";
$GROUP_CREATION = "_waiting_creation_%";
$GROUP_RENEWALL = "_waiting_renewall_%";
$ID_APPLICATION = 2;
global $ID_APPLICATION;

$mail_list = array();

//récupération des valideurs
$tmp_validator_users_list = $SOAP_CLIENT->getUserGroupsWithUsers($GROUP_VALIDATOR,$FILTERS_GROUPS);
if(count($tmp_validator_users_list) > 0){
	foreach($tmp_validator_users_list as $key => $value){
		$tmp = explode('_',$value['group_name']);
		
		//valideurs ICF
		if($tmp[count($tmp) - 2] == "ICF") {
			$mail_list[$tmp[count($tmp) - 1]]['validators_icf'] = $value['users'];
		}
		
		//valideurs normaux
		$mail_list[$tmp[count($tmp) - 1]]['validators'] = $value['users'];
	}
}

//récuperation des utilisateurs en attente de création
$tmp_creation_users_list = $SOAP_CLIENT->getUserGroupsWithUsers($GROUP_CREATION,$FILTERS_GROUPS);
if(count($tmp_creation_users_list) > 0){
	foreach($tmp_creation_users_list as $key => $value){
		$tmp = explode('_',$value['group_name']);
		
		//si dans groupe _waiting_creation_ICF_#
		if($tmp[count($tmp) - 2] == 'ICF') {
			$mail_list[$tmp[count($tmp) - 1]]['creation_icf'] = $value['users'];
		}
		else {
			$mail_list[$tmp[count($tmp) - 1]]['creation'] = $value['users'];
		}
	}
}

//Récuperation des utilisateurs en attente de renouvellement
$tmp_renewall_users_list = $SOAP_CLIENT->getUserGroupsWithUsers($GROUP_RENEWALL,$FILTERS_GROUPS);
if(count($tmp_renewall_users_list) > 0){
	foreach($tmp_renewall_users_list as $key => $value){
		$tmp = explode('_',$value['group_name']);
		
		//si dans groupe _waiting_renewall_ICF_#
		if($tmp[count($tmp) - 2] == 'ICF') {
			$mail_list[$tmp[count($tmp) - 1]]['renewall_icf'] = $value['users'];
		}
		else {
			$mail_list[$tmp[count($tmp) - 1]]['renewall'] = $value['users'];
		}
	}
}

//demande à l'echelon superieur si pas de reponse du valideur
foreach($mail_list as $key => $value){
	if($key == 2)continue;
	
	$parent = NULL;
	
	//traitement pour la creation
	if(isset($value['creation'])){
		foreach($value['creation'] as $user){
			$tmp = explode(" ",$user['creation_date']);
			$days_left = (strtotime(date("Y-m-d")) - strtotime($tmp[0])) / (60 * 60 * 24);
			if($days_left > 8){
				$parent_levels_to_complete = floor($days_left / 8);
				
				//recherche du parent si besoin
				if($parent == NULL){
					$parents_list = $SOAP_CLIENT->getAllParentList($key,array());
					for($i = 0 ; $i < count($parents_list) && $parent_levels_to_complete > 0; $i++){
						//si le parent n'as pas de valideur, on le saute
						if(!isset($mail_list[$parents_list[$i]]['validators'])) continue; 

						//si le groupe de creation n'existe pas, 
						//on le creer en ajoutant l'utilisateur
						if(!isset($mail_list[$parents_list[$i]]['creation'])){
							$mail_list[$parents_list[$i]]['creation'] = array($user);
							addUserToWaitingGroup($user,'_waiting_creation_'.$parents_list[$i]);
						}
						else{	
							//recherche si l'utilisateur est deja dans le groupe
							$in = false;
							foreach($mail_list[$parents_list[$i]]['creation'] as $tmp_user){
								if($tmp_user['id'] == $user['id']){
									$in = true;
								}
							}
							if(!$in){
								$mail_list[$parents_list[$i]]['creation'][] = $user;
								addUserToWaitingGroup($user,'_waiting_creation_'.$parents_list[$i]);
							}
						}
						$parent_levels_to_complete--;
					}
				}
				
				$mail_list[$parent]['creation'][] = $user;
			}
		}
	}
	
	//traitement pour la creation ICF
	if(isset($value['creation_icf'])){
		foreach($value['creation_icf'] as $user){
			$tmp = explode(" ",$user['creation_date']);
			$days_left = (strtotime(date("Y-m-d")) - strtotime($tmp[0])) / (60 * 60 * 24);
			if($days_left > 8){
				$parent_levels_to_complete = floor($days_left / 8);
				
				//recherche du parent si besoin
				if($parent == NULL){
					$parents_list = $SOAP_CLIENT->getAllParentList($key,array());
					for($i = 0 ; $i < count($parents_list) && $parent_levels_to_complete > 0; $i++){
						//si le parent n'as pas de valideur, on le saute
						if(!isset($mail_list[$parents_list[$i]]['validators_icf'])) continue; 

						//si le groupe de creation_icf n'existe pas, 
						//on le creer en ajoutant l'utilisateur
						if(!isset($mail_list[$parents_list[$i]]['creation_icf'])){
							$mail_list[$parents_list[$i]]['creation_icf'] = array($user);
							addUserToWaitingGroup($user,'_waiting_creation_ICF_'.$parents_list[$i]);
						}
						else{	
							//recherche si l'utilisateur est deja dans le groupe
							$in = false;
							foreach($mail_list[$parents_list[$i]]['creation_icf'] as $tmp_user){
								if($tmp_user['id'] == $user['id']){
									$in = true;
								}
							}
							if(!$in){
								$mail_list[$parents_list[$i]]['creation_icf'][] = $user;
								addUserToWaitingGroup($user,'_waiting_creation_ICF_'.$parents_list[$i]);
							}
						}
						$parent_levels_to_complete--;
					}
				}
				
				$mail_list[$parent]['creation_icf'][] = $user;
			}
		}
	}
	
	//traitement pour le renouvellement
	if(isset($value['renewall'])){
		foreach($value['renewall'] as $user){
			$tmp = explode(" ",$user['creation_date']);
			$days_left = (strtotime(date("Y-m-d")) - strtotime($tmp[0])) / (60 * 60 * 24);
			if($days_left > 8){
				
				$parent_levels_to_complete = $days_left % 8;
				
				//recherche du parent si besoin
				if($parent == NULL){
					$parents_list = $SOAP_CLIENT->getAllParentList($key,array());
					for($i = 0 ; $i < count($parents_list) && $parent_levels_to_complete > 0; $i++){
						//si le parent n'as pas de valideur, on le saute
						if(!isset($mail_list[$parents_list[$i]]['validators'])) continue; 
						
						
						//si le groupe de creation n'existe pas, 
						//on le creer en ajoutant l'utilisateur
						if(!isset($mail_list[$parents_list[$i]]['renewall'])){
							$mail_list[$parents_list[$i]]['renewall'] = array($user);
							addUserToWaitingGroup($user,'_waiting_creation_'.$parents_list[$i]);
						}
						else{	
							//recherche si l'utilisateur est deja dans le groupe
							$in = false;
							foreach($mail_list[$parents_list[$i]]['renewall'] as $tmp_user){
								if($tmp_user['user_id'] == $user['user_id']){
									$in = true;
								}
							}
							if($in){
								$mail_list[$parents_list[$i]]['renewall'][] = $user;
								addUserToWaitingGroup($user,'_waiting_creation_'.$parents_list[$i]);
							}
						}
						$parent_levels_to_complete--;
					}
				}
				
				$mail_list[$parent]['renewall'][] = $user;
			}
		}
	}
	
	//traitement pour le renouvellement ICF
	if(isset($value['renewall_icf'])){
		foreach($value['renewall_icf'] as $user){
			$tmp = explode(" ",$user['creation_date']);
			$days_left = (strtotime(date("Y-m-d")) - strtotime($tmp[0])) / (60 * 60 * 24);
			if($days_left > 8){
				
				$parent_levels_to_complete = $days_left % 8;
				
				//recherche du parent si besoin
				if($parent == NULL){
					$parents_list = $SOAP_CLIENT->getAllParentList($key,array());
					for($i = 0 ; $i < count($parents_list) && $parent_levels_to_complete > 0; $i++){
						//si le parent n'as pas de valideur, on le saute
						if(!isset($mail_list[$parents_list[$i]]['validators_icf'])) continue; 
						
						
						//si le groupe de creation n'existe pas, 
						//on le creer en ajoutant l'utilisateur
						if(!isset($mail_list[$parents_list[$i]]['renewall_icf'])){
							$mail_list[$parents_list[$i]]['renewall_icf'] = array($user);
							addUserToWaitingGroup($user,'_waiting_creation_'.$parents_list[$i]);
						}
						else{	
							//recherche si l'utilisateur est deja dans le groupe
							$in = false;
							foreach($mail_list[$parents_list[$i]]['renewall_icf'] as $tmp_user){
								if($tmp_user['user_id'] == $user['user_id']){
									$in = true;
								}
							}
							if($in){
								$mail_list[$parents_list[$i]]['renewall_icf'][] = $user;
								addUserToWaitingGroup($user,'_waiting_creation_ICF_'.$parents_list[$i]);
							}
						}
						$parent_levels_to_complete--;
					}
				}
				
				$mail_list[$parent]['renewall'][] = $user;
			}
		}
	}
}

/*
echo "<pre>";
//print_r($mail_list);
echo "</pre>";
*/

//envoi des mails
$validator_send_mail = array();
foreach($mail_list as $key => $value){
	if(!isset($value['validators']) and !isset($value['validators_icf'])) continue;
	echo '<pre>';
	print_r($value);
	echo '</pre>';
	
	$creation_number = 0;
	if(isset($value['creation'])) {
		$creation_number = count($value['creation']);
	}
	$creationICF_number = 0;
	if(isset($value['creation_icf'])) {
		$creationICF_number = count($value['creation_icf']);
	}
	$renewall_number = 0;
	if(isset($value['renewall'])) {
		$renewall_number = count($value['renewall']);
	}
	$renewallICF_number = 0;
	if(isset($value['renewall_icf'])) {
		$renewallICF_number = count($value['renewall_icf']);
	}
	// if($creation_number == 0 && $renewall_number == 0 && $creationICF_number == 0 && $renewallICF_number == 0) continue;
		
	// En-têtes
	$email_auteur = 'inscription.intranet@apelnationale.fr';
	$email_reply = 'inscription.intranet@apelnationale.fr';
	$headers = 'From: '.$email_auteur.' <'.$email_auteur.'>'."\n";
	$headers .='Reply-To: '.$email_reply."\n"; 
	$headers .= 'Content-Type: text/html; charset="utf-8"'."\n";
	$headers .= 'Content-Transfer-Encoding: 8bit'."\n\n";
	
	$object = "Demandes d’inscription à l’intranet en attente";
	
	$message = "<html><head></head><body>
				Bonjour.<br/><br/>
				Vous avez des demandes d’inscription (ou de renouvellement d’inscription) &agrave; l’intranet Apel en attente. 
				<br/>
				Pour y acc&eacute;der, connectez-vous &agrave; l’<a href='http://intranet.apel.fr'>intranet</a> avec vos identifiant et mot de passe, puis acc&eacute;dez &agrave; vos tableaux de validation dans la rubrique « mon compte »
				<br/><br/>
				<p><b>Apel Nationale</b><br />
				277 rue Saint Jacques<br />
				75240 Paris Cedex 05<br />
				<a href=\"http://www.apel.fr\">http://www.apel.fr</a><br />
				Tel : 01 53 73 73 90
				</p>
				</body></html>";
	
	if(isset($value['validators']) && ($creation_number != 0 or $renewall_number != 0)) {
		foreach($value['validators'] as $validator){
			$email_destinataire = stripslashes($validator['login']);
			//$email_destinataire = "publicite@micster.fr";
			
			if(in_array($validator['login'],$validator_send_mail)) continue;

			$validator_send_mail[] = $validator['login'];
			
			echo 'Demande normale : '.$validator['login'].' - '.$email_destinataire.'<br />';
			
			$result = mail($email_destinataire, $object, $message, $headers);
		}
	}
	if(isset($value['validators_icf']) && ($creationICF_number != 0 or $renewallICF_number != 0)) {
		$validator_send_mail_copy = array();
		foreach($value['validators_icf'] as $validator){
			$email_destinataire = stripslashes($validator['login']);
			//$email_destinataire = "publicite@micster.fr";
			
			if(in_array($validator['login'],$validator_send_mail)) continue;

			$validator_send_mail[] = $validator['login'];
			
			echo 'Demande ICF : '.$validator['login'].' - '.$email_destinataire.'<br />';
			
			$result = mail($email_destinataire, $object, $message, $headers);
		}
	}
}

pre($validator_send_mail);

function addUserToWaitingGroup($user,$group_name){
	global $SOAP_CLIENT;
	global $ID_APPLICATION;
	
	$structure_group_name = $group_name;
	$id_structure_group = $SOAP_CLIENT->getGroupIdByGroupNameAndApplicationId($structure_group_name, $ID_APPLICATION);
	if($id_structure_group == -1)
		$id_structure_group = $SOAP_CLIENT->addUserGroup($structure_group_name, $ID_APPLICATION);
	$SOAP_CLIENT->addUserToGroup($user['id'], $id_structure_group);	
}
?>